package cn.gjculture.shopping.api.aspect;

import cn.gjculture.shopping.api.entity.PageInfo;
import cn.gjculture.shopping.api.entity.Return;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Aspect
@Component
public class PageAspect {


    @Pointcut("execution(* cn.gjculture.shopping.api.controller.*.query*(..))")
    public void queryController() {
    }

    @Around(value = "queryController()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object[] objects = point.getArgs();
        PageInfo info = null;
        if (objects.length > 0) {
            for (Object obj : objects) {
                if (obj instanceof PageInfo) {
                    PageInfo pageInfo = (PageInfo) obj;
                    if (pageInfo != null && pageInfo.getCurrentPage() >= 0 && pageInfo.getPageSize() > 0) {
                        info = pageInfo;
                        if (!StringUtils.isEmpty(pageInfo.getOrderBy())) {
                            PageHelper.startPage(pageInfo.getCurrentPage(), pageInfo.getPageSize(), pageInfo.getOrderBy());
                        } else {
                            PageHelper.startPage(pageInfo.getCurrentPage(), pageInfo.getPageSize(), true);
                        }
                    }
                }
            }
        }
        Object ret = point.proceed();
        if (info != null && ret instanceof Return) {
            Return<Page> retObject  = (Return) ret;
            if(retObject.getData()!=null){
                info.setCurrentPage(retObject.getData().getPageNum());
                info.setPages(retObject.getData().getPages());
                info.setTotal(retObject.getData().getTotal());
                retObject.setPageInfo(info);
            }
        }
        return ret;
    }

}
